﻿@inject IHttpService _httpService
@inject NavigationManager NavigationManager
@inject IJSRuntime JS
@inject IDataCacheService _dataCatcheService
@inject IStructuredDataService _structuredDataService
@inject IPopupService PopupService

@implements IDisposable

@if (string.IsNullOrWhiteSpace(Model.Name) == false)
{
    <CnGalWebSite.Shared.MasaComponent.Shared.Cards.TitleTip Title="@("目录 - "+Model.Name)" Description="@Model.BriefIntroduction" Image="@Model.MainPicture"/>
}
else
{
    <CnGalWebSite.Shared.MasaComponent.Shared.Cards.TitleTip/>
}

@if (isNotFound)
{
    <NotFoundCard>
        <h1 class="text-center title-large">找不到这个收藏夹哦......</h1>
        <div class="text-center">可以在前往个人空间->收藏夹->编辑->设置收藏夹公开</div>
    </NotFoundCard>
}
else
{
    @if (_dataCatcheService.FavoriteFolderIndexPageCatche.Check(Id) || isReady)
    {
        <div class="row" itemscope itemtype="http://schema.org/Movie">
            <div class="col-12 mb-4">
                @if (Model.IsHidden == true)
                {
                    <CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaAlert Type="AlertTypes.Warning" Class="mb-3">
                        当前目录处于隐藏状态，如果你看到了这个提示，请立即联系管理员
                    </CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaAlert>
                }

                <div>
                    <CnGalWebSite.Shared.MasaComponent.PC.FavoriteFolders.MainCard Model="Model" OnRevoke="OnRevoke" OnPreEdit="OnPreEdit" />
                </div>
            </div>
            @if (_dataCatcheService.IsApp)
            {
                <div class="col-12 col-lg-4 ">

                    <CnGalWebSite.Shared.MasaComponent.PC.Users.MainInforCard Model="Model.UserInfor" Small />

                    <div class="mb-4">
                        <CnGalWebSite.Shared.MasaComponent.PC.FavoriteFolders.BasicInforCard Model="Model" OnRevoke="OnRevoke" />
                    </div>

                </div>
                <div class="col-12 col-lg-8">

                    <CnGalWebSite.Shared.MasaComponent.PC.FavoriteFolders.RelevancesCard Model="Model" />
                </div>
            }
            else
            {
                <div class="col-12 col-lg-8  order-2 order-lg-1 ">

                    <CnGalWebSite.Shared.MasaComponent.PC.FavoriteFolders.RelevancesCard Model="Model" />
                </div>
                <div class="col-12 col-lg-4 order-1 order-lg-2">
                    <CnGalWebSite.Shared.MasaComponent.PC.Users.MainInforCard Model="Model.UserInfor" />

                    <div class="mb-4">
                        <CnGalWebSite.Shared.MasaComponent.PC.FavoriteFolders.BasicInforCard Model="Model" OnRevoke="OnRevoke" />
                    </div>
                </div>
            }

        </div>
    }
    else
    {
        <CnGalWebSite.Components.Progressings.ProgressingCard Page />

    }

}
@if (isFirstLoad == false)
{
    <CnGalWebSite.Shared.MasaComponent.Shared.Cards.NavLoadingCard IsLoading="isLoading" />

}

<CnGalWebSite.Shared.MasaComponent.Shared.Components.TrackEvent DataType="TrackEventDataType.FavoriteFolder" EventType="TrackEventType.View" ObjectId="@Model.Id.ToString()"
                                                                ObjectName="@Model.Name" />

@code {

    [Parameter]
    public string Id { get; set; }

    bool isReady = false;
    bool isLoading = false;
    bool isNotFound = false;
    bool isFirstLoad = true;
    public string CurrentUserRank { get; set; }

    public FavoriteFolderViewModel Model { get; set; } = new FavoriteFolderViewModel();


    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }


    public bool IsAdmin { get; set; } = false;
    public bool CanDeleted { get; set; }
    string LastLookName = "";

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
        {
            NavigationManager.LocationChanged -= LocationChanged;
            NavigationManager.LocationChanged += LocationChanged;
            isFirstLoad = false;
        }
    }
    protected override async Task OnInitializedAsync()
    {
        await Refresh();
    }
    public async Task Refresh()
    {
        try
        {
            isNotFound = false;
            //获取词条信息
            Model = await _dataCatcheService.FavoriteFolderIndexPageCatche.GetCache(Id);
            //判断如果名称为空则返回主页
            if (string.IsNullOrWhiteSpace(Model.Name))
            {
                NavigationManager.NavigateTo("/");
            }

            var userState = await authenticationStateTask;
            var user = userState.User;
            if (user.Identity.Name == Model.UserInfor.Name)
            {
                Model.Authority = true;
                CanDeleted = true;
            }
            if (user.IsInRole("Editor"))
            {
                Model.Authority = true;
            }

            //生成轮播结构数据
            await GenerateCarouselStructuredDataJson();

            isReady = true;
            //StateHasChanged();

        }
        catch (Exception exc)
        {
            isNotFound = true;
            isReady = true;
            StateHasChanged();
        }
    }

    public async Task GenerateCarouselStructuredDataJson()
    {
        var urls = new List<string>();
        urls.AddRange(Model.Objects.Where(s => s.entry != null).Select(s => NavigationManager.BaseUri + "entries/" + s.entry.Id));
        urls.AddRange(Model.Objects.Where(s => s.article != null).Select(s => NavigationManager.BaseUri + "articles/" + s.article.Id));
        urls.AddRange(Model.Objects.Where(s => s.Video != null).Select(s => NavigationManager.BaseUri + "videos/" + s.Video.Id));
        await _structuredDataService.SetStructuredData(urls);
    }

    private async Task OnRevoke(Operation operation)
    {
        var ret = await PopupService.ConfirmAsync("确认撤销编辑", "撤销编辑后会删除数据，无法恢复，请谨慎操作");
        if (ret == false)
        {
            return;
        }
        //上传
        try
        {
            var obj = await _httpService.PostAsync<RevokeExamineModel, Result>("api/favorites/RevokeExamine", new RevokeExamineModel { Id = Model.Id, ExamineType = operation });
            //判断结果
            if (obj.Successful == false)
            {
                await PopupService.ToastErrorAsync("撤销审核请求失败", obj.Error);
            }
            else
            {
                await PopupService.ToastSuccessAsync("撤销审核请求成功", "撤销审核请求成功");
                //修改各部分编辑状态
                switch (operation)
                {
                    case Operation.EditFavoriteFolderMain:
                        Model.MainState = EditState.Normal;
                        break;

                }
                _dataCatcheService.FavoriteFolderIndexPageCatche.Clean(Id);
                Refresh();
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "撤销审核请求失败");
        }
    }

    public void OnPreEdit(bool value)
    {
        Model.IsEdit = value;
        StateHasChanged();

    }


    public async void LocationChanged(object sender, LocationChangedEventArgs args)
    {
        if (Id != Model.Id.ToString())
        {
            if (_dataCatcheService.FavoriteFolderIndexPageCatche.Check(Id) == false)
            {
                isLoading = true;
                StateHasChanged();
                await Refresh();
                isLoading = false;
                StateHasChanged();
            }
            else
            {
                await Refresh();
            }

        }
    }

    #region 释放实例

    public void Dispose()
    {

        NavigationManager.LocationChanged -= LocationChanged;

        GC.SuppressFinalize(this);
    }
    #endregion
}
